'''
行业分析
'''
import datetime

import pandas as pd
from flask import jsonify, request

from db.dao import IndustrySectorFundsDao, ConceptRankingListDao, MarketWorkDayDao
from utils.util import FlaskTool, CalculationTool
from web import custom


@custom.route('/concept/fund/ranking')
def conceptBank():
    '''
    股票行业单日涨幅查询
    :return:
    '''
    weeks = request.args.get('weeks', type=int)
    tops = request.args.get('tops', type=int)
    trading_day_list = MarketWorkDayDao().queryLastWorkDay(datetime.date.today(), limit=weeks * 5)
    listResult = []
    if trading_day_list:
        for startDate in trading_day_list:
            list = ConceptRankingListDao().findByDateOrderByTOP(date=startDate, limit=tops)
            if list:
                for conceptBank in list:
                    conceptBank['groupname'] = startDate
                    conceptBank['industry_name'] = conceptBank.get('concept_name')
                    conceptBank['industry_code'] = conceptBank.get('concept_code')
                    conceptBank['main_net_inflow'] = CalculationTool.str_of_num(conceptBank.get('main_net_inflow'))
                    listResult.append(conceptBank)

    return jsonify(listResult)


@custom.route('/concept/fund/inflow_top10_total')
def concept_funds_inflow_top10_total():
    '''
    近5日,10日资金汇总净流入前10的行业  todo pandas计算
    :return:
    '''
    weeks = request.args.get('weeks', type=int)
    tops = request.args.get('tops', type=int)
    pageNo = request.args.get('page', type=int)
    pageSize = request.args.get('rows', type=int)

    trading_day_list = MarketWorkDayDao().queryLastWorkDay(datetime.date.today(), limit=weeks * 5)
    if trading_day_list:
        startDate = trading_day_list[-1]
        list = ConceptRankingListDao().findTOPByDate(date=startDate)

    if list:
        model_list = FlaskTool.modelList(list)
        records = pd.DataFrame.from_records(model_list, exclude=['id', 'leading_stock_code', 'leading_stock_name'])
        create_time_groupby = records.sort_values(by=['create_date', 'main_net_inflow'],
                                                  ascending=[False, False]).groupby(['create_date']).head(tops)

        stock_counts = create_time_groupby['concept_name'].value_counts()
        inflow_sum = create_time_groupby.groupby(['concept_name'])['main_net_inflow'].sum().sort_values(
            ascending=False)

        records_uniq = records[['concept_name', 'concept_code']].drop_duplicates(['concept_code'], keep='last')
        stock_counts_pd = stock_counts.rename_axis('concept_name').reset_index(name='count')
        inflow_sum_pd = inflow_sum.rename_axis('concept_name').reset_index(name='inflow')
        pd_merge = records_uniq.merge(stock_counts_pd).merge(inflow_sum_pd)
        pd_merge = pd_merge[(pageNo - 1) * pageSize: (pageNo - 1) * pageSize + pageSize]
        to_dict = pd_merge.to_dict('records')
        if to_dict:
            for conceptBank in to_dict:
                conceptBank['inflow_str'] = CalculationTool.str_of_num(conceptBank.get('inflow'))

    return jsonify(to_dict)


@custom.route('/concept/ranking/time')
def concept_rank_time():
    pagination = ConceptRankingListDao().queryByPage(request.args)
    items = pagination.items
    for item in items:
        inflow = getattr(item, 'main_net_inflow')
        setattr(item, 'main_net_inflow', CalculationTool.str_of_num(inflow))
    return jsonify(FlaskTool.paginatioToList(pagination))
